package com.changeover.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.changeover.dao.IUserDao;
import com.changeover.domain.User;
import com.changeover.domain.UserRole;

@Service("userDetailService")
@Transactional(readOnly = true)
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private IUserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
        DataAccessException {
        User user = userDao.getUser(username);
        UserDetails ud = null;
        System.out.println(user);
        if (user != null) {
            Collection<UserRole> roles = user.getRoles();
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (UserRole userRole : roles) {
                System.out.println(userRole.getRoleName());
                authorities.add(new GrantedAuthorityImpl(userRole.getRoleName()));
            }
            ud = new org.springframework.security.core.userdetails.User(username, user.getPasswd(),
                true, true, true, true, authorities);
        }
        return ud;
    }

}
